// standard headers
#include <ctime>
#include <string>
#include <vector>

// custom headers
#include "..\include\file\outfile.h"
#include "..\include\logger.h" // matching header

// ==================================
//     SINGLETON IMPLEMENTATION
// ==================================

Logger* Logger::Instance()
{
    // Meyers singleton
    static Logger obj;
    return &obj;
}

Logger::Logger() 
{
	filePath_ = "runtime.log";
	logFile_.open(filePath_);
}

Logger::~Logger() {}
Logger::Logger(const Logger& other) {}
Logger& Logger::operator=(const Logger& other) { return *this; }


// ==================================
//        PROCESSING ENTRIES
// ==================================

void Logger::addEntry(EntryType entryType, std::string text)
{
	switch (entryType) {
        case ERROR :
            text = formatErrorEntry(text);
            break;
        case INFO :
            text = formatInfoEntry(text);
            break;
    }
	
	text = getTimeAndDate() + " - " + text;    
	writeToFile(text);
}

std::string Logger::formatErrorEntry(std::string text)
{
	return "ERROR: " + text;
}

std::string Logger::formatInfoEntry(std::string text)
{
	return text;
}

std::string Logger::getTimeAndDate()
{
	time_t rawtime;
	tm* timeinfo;

	time(&rawtime);
	timeinfo = localtime (&rawtime);
	return asctime(timeinfo);
}


// ==================================
//           WRITE TO...
// ==================================

void Logger::writeToFile(std::string text)
{
	if (logFile_.is_open()) {
		logFile_.puts(text.c_str());
		logFile_.puts("\r\n");

		// After adding the new entry save the log file by closing and opening
		// again in append mode in order to prevent losing the information if 
		// the application crashes.
		logFile_.close();
		logFile_.open(filePath_, OutFile::app);
	}
}
